package org.amphiprion.descentv2assistant.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

public class SectionMap<S, O> {
	ArrayList<SectionMap<S, O>.Item> list = new ArrayList();
	LinkedHashMap<S, SectionMap<S, O>.Group> map = new LinkedHashMap();

	public int add(S paramS, O paramO) {
		int i = this.list.size();
		Group localGroup;
		if (!this.map.containsKey(paramS)) {
			localGroup = new Group(this.map.size());
			localGroup.fromIndex = i;
			this.map.put(paramS, localGroup);
		} else {
			localGroup = this.map.get(paramS);
		}

		Item localItem = new Item(paramO, localGroup.groupId);
		this.list.add(localItem);
		localGroup.length = (1 + localGroup.length);
		return i;
	}

	public int getCountForGroup(int sectionIndex) {
		Group localGroup = this.map.get(Integer.valueOf(sectionIndex));
		if (localGroup == null) {
			localGroup = (Group) ((Map.Entry) this.map.entrySet().toArray()[sectionIndex]).getValue();
		}
		if (localGroup != null) {
			return localGroup.length;
		} else {
			return 0;
		}
	}

	public int getFirstIndexInSection(int sectionIndex) throws IndexOutOfBoundsException {

		Object key = new ArrayList(this.map.keySet()).get(sectionIndex);
		Group grp = this.map.get(key);
		return grp.fromIndex;
	}

	public int getSectionFromIndex(int sectionIndex) throws IndexOutOfBoundsException {
		return this.list.get(sectionIndex).groupId;
	}

	public Object[] getSections() {
		return this.map.keySet().toArray();
	}

	private final class Item {
		final int groupId;
		final O obj;

		Item(O localObject, int id) {
			this.obj = localObject;
			this.groupId = id;
		}
	}

	private final class Group {
		int fromIndex = 0;
		public final int groupId;
		int length = 0;

		Group(int id) {
			this.groupId = id;
		}
	}
}